#!/bin/bash
#
# This script prints the information stored in TechnicalInformationHandlers
# to stdout.
#
# FracPete, $Revision$

# the usage of this script
function usage()
{
   echo
   echo "${0##*/} -d <dir> [-w <jar>] [-p|-b] [-h]"
   echo
   echo "Prints the information stored in TechnicalInformationHandlers to stdout."
   echo
   echo " -h   this help"
   echo " -d   <dir>"
   echo "      the directory to look for packages, must be the one just above"
   echo "      the 'weka' package, default: $DIR"
   echo " -w   <jar>"
   echo "      the weka jar to use, if not in CLASSPATH"
   echo " -p   prints the information in plaintext format"
   echo " -b   prints the information in BibTeX format"
   echo
}

# generates a filename out of the classname TMP and returns it in TMP
# uses the directory in DIR
function class_to_filename()
{
  TMP=$DIR"/"`echo $TMP | sed s/"\."/"\/"/g`".java"
}

# variables
DIR="."
PLAINTEXT="no"
BIBTEX="no"
WEKA=""
TECHINFOHANDLER="weka.core.TechnicalInformationHandler"
TECHINFO="weka.core.TechnicalInformation"
CLASSDISCOVERY="weka.core.ClassDiscovery"

# interprete parameters
while getopts ":hpbw:d:" flag
do
   case $flag in
      p) PLAINTEXT="yes"
         ;;
      b) BIBTEX="yes"
         ;;
      d) DIR=$OPTARG
         ;;
      w) WEKA=$OPTARG
         ;;
      h) usage
         exit 0
         ;;
      *) usage
         exit 1
         ;;
   esac
done

# either plaintext or bibtex
if [ "$PLAINTEXT" = "$BIBTEX" ]
then
   echo
   echo "ERROR: either -p or -b has to be given!"
   echo
   usage
   exit 2
fi

# do we have everything?
if [ "$DIR" = "" ] || [ ! -d "$DIR" ]
then
   echo
   echo "ERROR: no directory or non-existing one provided!"
   echo
   usage
   exit 3
fi

# generate Java call
if [ "$WEKA" = "" ]
then
  JAVA="java"
else
  JAVA="java -classpath $WEKA"
fi
if [ "$PLAINTEXT" = "yes" ]
then
  CMD="$JAVA $TECHINFO -plaintext"
elif [ "$BIBTEX" = "yes" ]
then
  CMD="$JAVA $TECHINFO -bibtex"
fi

# find packages
TMP=`find $DIR -mindepth 1 -type d | grep -v CVS | sed s/".*weka"/"weka"/g | sed s/"\/"/./g`
PACKAGES=`echo $TMP | sed s/" "/,/g`

# get technicalinformationhandlers
TECHINFOHANDLERS=`$JAVA weka.core.ClassDiscovery $TECHINFOHANDLER $PACKAGES | grep "\. weka" | sed s/".*weka"/weka/g`

# output information
echo
for i in $TECHINFOHANDLERS
do
  TMP=$i;class_to_filename

  # exclude internal classes
  if [ ! -f $TMP ]
  then
    continue
  fi

  $CMD -W $i
  echo
done

